package cn.calm.user.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.log4j.Logger;

import cn.calm.commons.dao.QueryConditionBuilder;
import cn.calm.commons.entity.BaseEntity;
import cn.calm.commons.service.defaultimpl.DefaultServiceImpl;
import cn.calm.entity.Menu;
import cn.calm.entity.User;
import cn.calm.user.service.IMenuService;

public class MenuServiceImpl<T extends Menu> extends DefaultServiceImpl<T>
		implements IMenuService<T> {
	private static final Logger logger = Logger
			.getLogger(IMenuService.class);

	@Override
	public T loadByUserAndParent(final User u, final T t) {
		logger.debug("loadByUserAndParent start");
		try {

			List<T> list=baseDao.list(Menu.class, new QueryConditionBuilder<T>() {

				@Override
				public void query(CriteriaBuilder r, CriteriaQuery<?> query,Root<? extends BaseEntity> root) {
//					Root<Menu> root = query.from(Menu.class);
					Path<User> path = root.get("user");
					Predicate preUser = r.equal(path, u);
					Predicate preParent;
					if (t.getId() == null || "null".equals(t.getId())) {
						preParent = r.isNull(root.get("parent"));
					} else {
						Menu parent = baseDao.load(Menu.class, t.getId());
						preParent=r.equal(root.get("parent"), parent);
					}
					query.where(preUser,preParent);
				}
			});
			if(list!=null && list.size()>0){
				return list.get(0);
			}
			// QueryCondition condition = new QueryCondition();
			// condition.andEq("user", u);
			// if (t.getId() == null || "null".equals(t.getId())) {
			// condition.andIsNull("parent");
			// temp = baseDao.loadByCondition(Menu.class, condition);
			// } else {
			// temp = baseDao.load(Menu.class, t.getId());
			// // condition.andEq("parent", temp);
			// }
//			if (temp.getParent() == null) {
//				temp.setId(null);
//			}
			// T temp=baseDao.loadByCondition(Menu.class, condition);
			return null;
		} finally {
			logger.debug("loadByUserAndParent end");
		}
	}
}
